package predictionEngine;

import java.util.List;

public class NumericSplit implements ISplit {
    private int attribute;
    private double value, strength;
    private String attributeName;

    public NumericSplit(Dataset dataset,int attribute) {
        this.attribute=attribute;
        findBestSplit(dataset);
        attributeName = dataset.getAttribute(attribute).getName();
    }

    private void findBestSplit(Dataset dataset) {
        List<double[]> instances = dataset.getInstances();
        strength = 0;
        value = 0;
        int targetIndex = instances.get(0).length - 1;

        dataset.sortBy(attribute);

        double sT = 0;
        for (double[] instance : instances)
            sT += instance[targetIndex];
        double sRight = sT, sLeft = 0;
        int nT = instances.size();
        int nRight = nT, nLeft = 0;

        for (int i = 0; i < instances.size() -1; i++) {
            double[] instance = instances.get(i);
            double target = instance[targetIndex];
            double attValue = instance[attribute];
            double nextAttValue = instances.get(i + 1)[attribute];

            sLeft += target;
            sRight -= target;
            nLeft++;
            nRight--;

            if (attValue < nextAttValue) {
                double newStrength =
                    Math.pow(sLeft, 2) / nLeft + Math.pow(sRight, 2) / nRight;
                if (newStrength > strength) {
                    strength = newStrength;
                    value = (attValue + nextAttValue) / 2;
                }
            }

        }
    }

    public String toString() {
        return attributeName + " > " + value;
    }

    public boolean test(double[] instance) {
        return instance[attribute] > value;
    }

    public double getSplitValue() {
        return value;
    }

    public double getStrength() {
        return strength;
    }

    public int getAttribute() {
        return attribute;
    }
}
